import 'package:flutter/material.dart';
import 'package:framework/data/model/function_bean.dart';
import 'package:module_home/widgets/function_grid_item.dart';

/// 可复用的拖拽网格项组件
class DraggableGridItem extends StatelessWidget {
  final FunctionBean data;
  final int index;
  final bool isEditing;
  final VoidCallback onDelete;
  final ValueChanged<int> onReorder;

  const DraggableGridItem({
    super.key,
    required this.data,
    required this.index,
    required this.isEditing,
    required this.onDelete,
    required this.onReorder,
  });

  @override
  Widget build(BuildContext context) {
    return LongPressDraggable<int>(
      feedback: _DragFeedbackContent(data: data),
      childWhenDragging: _DragTargetContent(
        data: data,
        isDragging: true,
        isEditing: isEditing,
        onDelete: onDelete,
      ),
      data: index,
      child: DragTarget<int>(
        builder: (context, _, __) => _DragTargetContent(
          data: data,
          isDragging: false,
          isEditing: isEditing,
          onDelete: onDelete,
        ),
        onWillAccept: (_) => isEditing,
        onAccept: onReorder,
      ),
    );
  }
}

/// 拖拽反馈内容组件
class _DragFeedbackContent extends StatelessWidget {
  final FunctionBean data;

  const _DragFeedbackContent({required this.data});

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: FunctionGridItem(
        name: data.name,
        icon: data.icon,
        textSize: 10,
      ),
    );
  }
}

/// 拖拽目标内容组件
class _DragTargetContent extends StatelessWidget {
  final FunctionBean data;
  final bool isDragging;
  final bool isEditing;
  final VoidCallback onDelete;

  const _DragTargetContent({
    required this.data,
    required this.isDragging,
    required this.isEditing,
    required this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          alignment: Alignment.center,
          child: Opacity(
            opacity: isDragging ? 0.5 : 1.0,
            child: InkWell(
              onTap: onDelete,
              child: FunctionGridItem(
                name: data.name,
                icon: data.icon,
                textSize: 10,
              ),
            ),
          ),
        ),
        if (isEditing && data.edit == true)
          const Positioned(
            top: 0,
            right: 0,
            child: Icon(Icons.delete_forever, color: Colors.grey, size: 16),
          ),
      ],
    );
  }
}
